import 'package:built_collection/built_collection.dart';
import 'package:chopper/chopper.dart';
import 'package:flutter/material.dart';
import 'package:hello_flutter/demo/chopper_demo/data/post_api_service.dart';
import 'package:hello_flutter/demo/chopper_demo/model/built_post.dart';
import 'package:hello_flutter/demo/chopper_demo/page/detail_page.dart';
import 'package:provider/provider.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        centerTitle: true,
        title: Text('Materilal App Bar'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final newPost = BuiltPost((built) => built
            ..title = "NewTitle"
            ..body = "Body");
          final response =
              await Provider.of<PostApiService>(context).postPost(newPost);
          print(response.body);
        },
      ),
      body: _buildBody(context),
    );
  }

  FutureBuilder<Response> _buildBody(BuildContext context) =>
      FutureBuilder<Response<BuiltList<BuiltPost>>>(
        future: Provider.of<PostApiService>(context).getPosts(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return Center(
                child: Text('${snapshot.error}'),
              );
            }
            final posts = snapshot.data.body;
            return _buildPosts(context, posts);
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      );

  _buildPosts(BuildContext context, BuiltList<BuiltPost> posts) {
    return ListView.builder(
      itemCount: posts.length ?? 0,
      itemBuilder: (context, index) {
        return Card(
          child: ListTile(
            onTap: () {
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => DetailPage(posts[index].id)));
            },
            title: Text(posts[index].title),
            subtitle: Text(posts[index].body),
          ),
        );
      },
    );
  }
}
